package cn.lyq.card.ui.order

import android.content.Context
import android.content.Intent
import android.view.View
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import cn.lyq.card.R
import cn.lyq.card.base.BaseActivity
import cn.lyq.card.data.model.AddressInfo
import cn.lyq.card.data.model.DeviceInfo
import cn.lyq.card.data.src.Status
import cn.lyq.card.global.BusTag
import cn.lyq.card.manager.UserManager
import cn.lyq.card.ui.address.AddressManagerActivity
import cn.lyq.card.ui.web.WebPayActivity
import cn.lyq.card.utils.getVisibility
import cn.lyq.card.utils.loadUrl
import cn.lyq.card.utils.setClick
import cn.lyq.card.utils.toMoney
import com.blankj.utilcode.util.BusUtils
import com.blankj.utilcode.util.ToastUtils
import kotlinx.android.synthetic.main.act_order_confrim.*
import kotlinx.android.synthetic.main.item_device.*


class OrderConfirmActivity : BaseActivity() {

    private val mModel by lazy {
        getVM(OrderVM::class.java)
    }
    private val mInfo by lazy {
        intent.getSerializableExtra(KEY_INFO)
            ?.takeIf { it is DeviceInfo }
            ?.run { this as DeviceInfo }
    }
    private val mNum by lazy {
        intent.getIntExtra(KEY_NUM, 1)
    }
    private var mAddress: AddressInfo? = null

    companion object {
        private const val KEY_INFO = "INFO"
        private const val KEY_NUM = "NUM"

        @JvmStatic
        fun start(context: Context, info: DeviceInfo, num: Int) {
            val starter = Intent(context, OrderConfirmActivity::class.java)
                .putExtra(KEY_INFO, info)
                .putExtra(KEY_NUM, num)
            context.startActivity(starter)
        }
    }

    override fun getLayoutId(): Int {
        return R.layout.act_order_confrim
    }

    override fun initView() {
        super.initView()
        setMyTitle(R.string.str_confirm_order)

        itemDevice.setBackgroundColor(ContextCompat.getColor(this, R.color.bg_white))
        itemDevice.elevation = 0f
        tvBuyDevice.visibility = View.GONE

        tvAliPay.isSelected = true
    }

    override fun initListener() {
        super.initListener()
        tvAliPay.setClick {
            tvAliPay.isSelected = true
            tvWeChatPay.isSelected = false
        }
        tvWeChatPay.setClick {
            tvAliPay.isSelected = false
            tvWeChatPay.isSelected = true
        }
        bgAddress.setClick {
            AddressManagerActivity.start(this, mAddress?.id ?: 0)
        }
        tvConfirm.setClick {
            if (mAddress == null) {
                ToastUtils.showShort(R.string.str_add_address_tip)
                return@setClick
            }
            toAddDeviceOrder()
        }
    }

    private fun toAddDeviceOrder() {
        mModel.addGoodsOrder(
            mInfo?.goodsId ?: 0,
            mNum,
            if (tvAliPay.isSelected) 1 else 2,
            mAddress?.id ?: 0,
            etRemark.text.toString().trim()
        )
            .observe(this, Observer {
                when (it?.status) {
                    Status.LOADING -> showLoading()
                    Status.SUCCESS -> {
                        WebPayActivity.start(this, it.requireData())
                        dismissLoading()
                        finish()
                    }
                    Status.ERROR -> {
                        dismissLoading()
                        ToastUtils.showShort(it.message.getMsg())
                    }
                }
            })

    }

    override fun initObserver() {
        super.initObserver()

        if (UserManager.addressInfo == null) {
            getAddress()
        } else {
            setAddress(UserManager.addressInfo)
        }
        setData()
    }

    @BusUtils.Bus(tag = BusTag.ADDRESS_SELECT, threadMode = BusUtils.ThreadMode.MAIN)
    fun setAddress(addressInfo: AddressInfo?) {
        mAddress = addressInfo
        if (addressInfo == null) {
            tvDefault.visibility = View.GONE
            tvUserName.visibility = View.GONE
            tvAddressDetail.setText(R.string.str_address_empty_tip)
        } else {
            tvDefault.visibility = getVisibility(!addressInfo.isDefault())
            tvUserName.visibility = View.VISIBLE
            tvUserName.text = addressInfo.getTitle()
            tvAddressDetail.text = addressInfo.getAddressStr()
        }
    }

    private fun setData() {
        mInfo?.let {
            imgDevice.loadUrl(it.img)
            tvName.text = "机具类型：${it.title ?: ""}"
            tvPrice.text = "机具价格：${it.price ?: ""}元/台"
        }
        setAmount()
    }

    private fun setAmount() {
        tvNum.text = mNum.toString()
        val price = mInfo?.price?.toDouble() ?: 0.0
        tvAmount.text = "￥${(price * mNum).toMoney()}(共${mNum}台)"
    }

    private fun getAddress() {
        mModel.getAddressList().observe(this, Observer {
            when (it?.status) {
                Status.SUCCESS -> {
                    UserManager.setDefaultAddress(it.requireData())
                    setAddress(UserManager.addressInfo)
                    dismissLoading()
                }
                Status.ERROR -> {
                    dismissLoading()
                    ToastUtils.showShort(it.message.getMsg())
                }
                else -> {
                }
            }
        })
    }

}